package com.distributor.interceptor;


import com.distributor.common.ReturnObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
//    @Autowired
//    private IBaseAppUserService iBaseAppUserService;

    public static final String LOGIN_TOKEN_KEY = "Token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return super.preHandle(request, response, handler);
        }
        //如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return super.preHandle(request, response, handler);
        }
        //从header中获取token
        String token = request.getHeader(LOGIN_TOKEN_KEY);

        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(LOGIN_TOKEN_KEY);
        }

        //token为空
        if (StringUtils.isBlank(token)) {
            SendMsgUtil.sendJsonMessage(response, new ReturnObject<>(401, "请先登录", ""));
            return false;
        } else {
//            BaseAppUser baseUsers = iBaseAppUserService.selectByToken(token);
//            if (baseUsers == null) {
//                SendMsgUtil.sendJsonMessage(response, new ReturnObject<>(401, "请先登录", ""));
//                return false;
//            } else {
//                BaseContextHandler.setUserID(baseUsers.getId().toString());
//                BaseContextHandler.setUsername(baseUsers.getUsername());
//                iBaseAppUserService.updateById(baseUsers);
//            }
        }
        return super.preHandle(request, response, handler);
    }
}
